<script src="http://code.google.com/apis/gears/gears_init.js" type="text/javascript" charset="utf-8"></script>
<script src="http://www.merkwelt.com/people/stan/geo_js/js/geo.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>

<script>

  var map;

    function initialize_map()
    {
        var myOptions = {
	      zoom: 4,
	      mapTypeControl: true,
	      mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	      navigationControl: true,
	      navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN},
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
	    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    }

    function initialize()
    {
	    if(geo_position_js.init())
	    {
		    document.getElementById('current').innerHTML="Receiving...";
		    geo_position_js.getCurrentPosition(show_position,function(){document.getElementById('current').innerHTML="Couldn't get location"},{enableHighAccuracy:true});
	    }
	    else
	    {
		    document.getElementById('current').innerHTML="Functionality not available";
	    }
    }

    var posizione_personale = 0;
    var raggio = 1000;
    var colore;
    var zoom;

    function calcolo_raggio() {
        var scelta = document.getElementById('slider').value;
        var rag = 0;
        if (scelta=="auto") {
            rag = 1000;
            colore = '#AA0000';
            zoom = 14;

        } else {
             rag = 300;
             colore = '#0000CC';
             zoom = 16;
        }
         raggio = rag;
    }

    var cir;
    var my_marker;

    function show_position(p)
    {
	    document.getElementById('current').innerHTML="latitude="+p.coords.latitude.toFixed(2)+" longitude="+p.coords.longitude.toFixed(2);
	    var pos=new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
        posizione_personale = pos;
	    map.setCenter(pos);
	    map.setZoom(14);

	    var infowindow = new google.maps.InfoWindow({
	        content: "<strong>You are here</strong>"
	    });

	    var marker = new google.maps.Marker({
	        position: pos,
	        map: map,
	        title:"You are here"
	    });
        my_marker = marker;
        calcolo_raggio();
        // Add circle overlay and bind to marker
        cir = new google.maps.Circle({
          map: map,
          radius: raggio,    // in metri
          fillColor: colore,
          strokeColor: colore
        });
        cir.bindTo('center', marker, 'position');

        //cir = circle;

	    google.maps.event.addListener(marker, 'click', function() {
	        infowindow.open(map,marker);
	    });
        split();
    }

    var markers = [];
    var geocoder = new google.maps.Geocoder();
    function codeAddress(ind, nam)
    {
        var address = ind;
        var name = nam;
        geocoder.geocode( { 'address': address}, function(results, status) {
           // if (status == google.maps.GeocoderStatus.OK) {
                var dist = google.maps.geometry.spherical.computeDistanceBetween(results[0].geometry.location, posizione_personale);
                calcolo_raggio();
                //alert(raggio);
                if (dist < raggio) {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        title: address,
                        animation: google.maps.Animation.DROP
                    });
                    markers.push(marker);
                    var lat = results[0].geometry.location.lat().toFixed(3);
                    var lng = results[0].geometry.location.lng().toFixed(3);
                    var infowindow = new google.maps.InfoWindow({
	                    content: '<table>'+
                                '<tr>'+
                                    '<td>'+
    		                            '<img src="http://www.trabiaplanet.it/img/tpl/icons/nu_farmacia.png">'+
                                    '</td>'+
                                    "<td>"+name+"<br><font size='1px'>("+lat+", "+lng+")</font></td>"+
                                '</tr>'+
                              '</table>'
	                });
                    google.maps.event.addListener(marker, 'click', function() {
	                infowindow.open(map,marker);
	                });
                }
           // }
        });
    }

    function clearOverlays()
    {
        if (markers) {
            for (i in markers) {
                markers[i].setMap(null);
            }
        }
    }

    function clear_circle() {
       cir.setMap(null);
        calcolo_raggio();
        cir = new google.maps.Circle({
          map: map,
          radius: raggio,    // in metri
          fillColor: colore,
          strokeColor: colore
        });
        cir.bindTo('center', my_marker, 'position');
        map.setZoom(zoom);
    }

    function split()
    {
        clearOverlays();
        var item = document.getElementById("address").value;
        var name = document.getElementById("name").value;
        var neighborhoods2 = item.split("+");                      //array di indirizzi
        var name2 = name.split("+");                                //array di nomi
        for (var i=0; i<neighborhoods2.length; i++) {
              codeAddress(neighborhoods2[i], name2[i]);
        }
    }

</script >

<body onload="initialize_map();initialize()">
	<div data-role="header">
        <h1>TEST</h1>
        <A HREF="javascript:history.go(0)">Refresh</A>
        <%= link_to 'Home', posts_path, "class" => "ui-btn-right", "data-icon" => "home" %>
    </div>

    <div data-role="content">

	    <select name="slider" id="slider" data-role="slider" onchange="clear_circle(); split()">
		<option value="auto">In Auto</option>
		<option value="piedi">A Piedi</option>
	    </select>

      <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
        <div id="current">Initializing...</div>
        <div id="map_canvas" style="height:400px"></div>
      </div>
    </div>
    <!-- RICAVARE GLI INDIRIZZI DAL DB E TRASMETTERLI ALLA FUNZIONE CHE FA LO SPLIT !-->
    <div id="nome" style="visibility:hidden"><input id="name" value="<% @posts.each do |post| %><%= post.title%> + <% end %>"></div>
    <div id="via" style="visibility:hidden"><input id="address" value="<% @posts.each do |post| %><%= post.body%> + <% end %>"></div>

<div data-role="footer" style="height: 30px"  data-position="fixed"></div>

</body>